------------------------------------------------------------------------
--  Get Blizzard infos, name and addon table
------------------------------------------------------------------------
local _, LootType = ...

------------------------------------------------------------------------
--  Variables
------------------------------------------------------------------------
local L = LibStub("AceLocale-3.0"):GetLocale("Broker_LootType")
local playerName
local blt

------------------------------------------------------------------------
--  Forward declaration for some functions
------------------------------------------------------------------------
local onClick
local onTooltipShow

------------------------------------------------------------------------
--  The Addon
------------------------------------------------------------------------
function LootType:OnLoad()
	self:RegisterEvent("PLAYER_LOGIN")
	self:RegisterEvent("PARTY_MEMBERS_CHANGED")
	self:RegisterEvent("RAID_ROSTER_UPDATE", "PARTY_MEMBERS_CHANGED")
	self:RegisterEvent("PARTY_LOOT_METHOD_CHANGED", "PARTY_MEMBERS_CHANGED")

	blt = LibStub("LibDataBroker-1.1"):NewDataObject("Broker_LootType", {
		type = "data source",
		icon = "Interface\\Buttons\\UI-GroupLoot-Dice-Up",
		text = "LootType",
		OnClick = onClick,
		OnTooltipShow = onTooltipShow,
	})
end

function LootType:PLAYER_LOGIN()
	playerName = UnitName("player")

	-- Fire once to get the correct text to show up
	self:PARTY_MEMBERS_CHANGED()
end

function LootType:PARTY_MEMBERS_CHANGED()
	local msg
 	-- local nrm = GetNumRaidMembers() + GetNumPartyMembers()
	-- if nrm > 0 then
	if UnitInRaid("player") or UnitInParty("player") then
		-- Update the text
		local lootmethod, partyID, raidID = GetLootMethod()
		local lootthreshold = GetLootThreshold()
		msg = ITEM_QUALITY_COLORS[lootthreshold].hex .. L[lootmethod]

		-- If we have a masterlooter, get her name
		if lootmethod == "master" then
			local unitID
			if partyID then -- masterlooter in own party
				unitID = partyID == 0 and "player" or "party"..partyID
			else -- masterlooter in raid
				unitID = "raid"..raidID
			end
			IsMasterLooter = UnitName(unitID)
		else
			IsMasterLooter = nil
		end
	else
		IsMasterLooter = nil
		msg = L["Inactive"]
	end
	blt.text = msg
end

------------------------------------------------------------------------
--  Menu functions
------------------------------------------------------------------------
local function onLootThresholdChange(self, arg1, arg2, checked)
	SetLootThreshold(arg1)
end

local function onLootMethodChange(self, arg1, arg2, checked)
	if arg1 == "master" then
		SetLootMethod(arg1, playerName, 1)
	else
		SetLootMethod(arg1)
	end
end

------------------------------------------------------------------------
--  Helper function to sort the submenus
------------------------------------------------------------------------
local function sortFunc(item1, item2)
	return item1.value < item2.value
end

local menu, menuFrame
local function menuCreate()
	-- Build table for loot threshold
	menu = {}
	menu[2] = L["Uncommon"]
	menu[3] = L["Rare"]
	menu[4] = L["Epic"]

	-- Submenu: Loot threshold
	local lootthreshold = { 
		text = L["Loot threshold"], 
		hasArrow = true,
		value = 0,
		GetCompareValue = function ()
			return GetLootThreshold()
		end
	}
	for key, value in pairs(menu) do
		local text = ITEM_QUALITY_COLORS[key].hex .. value
		local item = {
			text = text,
			func = onLootThresholdChange,
			arg1 = key,
			value = key,
		}
		table.insert(lootthreshold, item)

		-- nil out current key, value
		menu[key] = nil
	end
	table.sort(lootthreshold, sortFunc)

	-- Build table for loot methods
	menu[0] = "freeforall"
	menu[1] = "group"
	menu[2] = "needbeforegreed"
	menu[3] = "roundrobin"
	menu[4] = "master"

	-- Submenu: Loot methods
	local lootmethod = {
		text = L["Loot method"],
		hasArrow = true,
		value = 1,
		GetCompareValue = function ()
			local lootmethod, _, _ = GetLootMethod()
			return lootmethod
		end
	}
	for key, value in pairs(menu) do
		local text = L[value]
		local item = {
			text = text,
			func = onLootMethodChange,
			arg1 = value,
			value = key,
		}
		table.insert(lootmethod, item)

		-- nil out current key, value
		menu[key] = nil
	end
	table.sort(lootmethod, sortFunc)

	-- main menu
	wipe(menu)
	menu[0] = lootthreshold
	menu[1] = lootmethod
end

local function menuInit(self, level)
	level = level or 1

	-- Mainmenu, level 1
	if (level == 1) then
		for key, value in pairs(menu) do
			UIDropDownMenu_AddButton(value, level)
		end
	end

	-- Submenu, level 2
	if (level == 2) then
		local submenu = menu[UIDROPDOWNMENU_MENU_VALUE]
		local compare = submenu:GetCompareValue()
		for key, value in pairs(submenu) do
			if type(value) == "table" then
				value.checked = value.arg1 == compare
				UIDropDownMenu_AddButton(value, level)
			end
		end
	end
end

------------------------------------------------------------------------
--  Callbacks from LibDataBroker
------------------------------------------------------------------------
function onClick(self, button)
	if button == "RightButton" then
		if not menuFrame then 
			menuFrame = CreateFrame("Frame", "Broker_LootTypeMenu", UIParent, "UIDropDownMenuTemplate")
			menuCreate()
			UIDropDownMenu_Initialize(menuFrame, menuInit, "MENU")
		end
		ToggleDropDownMenu(1, nil, menuFrame, self, 20, 4)
	end
end

function onTooltipShow(tooltip)
	tooltip:AddLine("Broker: LootType")
	tooltip:AddLine(blt.text)
	if IsMasterLooter then
		tooltip:AddLine(IsMasterLooter)
	end
end
